package com.example.controller;

import com.example.model.DbConnection;
import com.example.model.User;
import com.example.model.UserRole;
import com.example.service.DbConnectionService;
import com.example.service.MetadataService;
import com.example.service.SqlTranslateService;
import com.example.service.UserService;
import com.example.util.RedisCacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/admin")
public class AdminController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private SqlTranslateService sqlTranslateService;
    
    @Autowired
    private DbConnectionService dbConnectionService;
    
    @Autowired
    private MetadataService metadataService;
    
    @Autowired
    private RedisCacheUtil redisCacheUtil;

    // 获取所有用户列表
    @GetMapping("/users")
    public ResponseEntity<?> getAllUsers(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize
    ) {
        try {
            // 构建响应数据，包含分页信息和用户列表
            Map<String, Object> response = new HashMap<>();
            response.put("records", userService.getPagedUsers(page, pageSize));
            response.put("total", userService.getUserCount());
            response.put("page", page);
            response.put("pageSize", pageSize);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "获取用户列表失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    // 获取指定角色的用户
    @GetMapping("/users/role/{role}")
    public ResponseEntity<?> getUsersByRole(
            @PathVariable String role,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize
    ) {
        try {
            // 构建响应数据，包含分页信息和用户列表
            Map<String, Object> response = new HashMap<>();
            response.put("records", userService.getPagedUsersByRole(role, page, pageSize));
            response.put("total", userService.getUserCountByRole(role));
            response.put("page", page);
            response.put("pageSize", pageSize);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "获取用户列表失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    // 更新用户角色
    @PutMapping("/users/{userId}/role")
    public ResponseEntity<?> updateUserRole(
            @PathVariable Long userId,
            @RequestBody Map<String, String> request) {
        try {
            String role = request.get("role");
            userService.updateUserRole(userId, role);
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "用户角色已更新");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    // 删除用户
    @DeleteMapping("/users/{userId}")
    public ResponseEntity<?> deleteUser(@PathVariable Long userId) {
        try {
            userService.deleteUser(userId);
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "用户已删除");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    // 获取所有转换历史记录（所有用户）
    @GetMapping("/history")
    public ResponseEntity<?> getAllHistory(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize
    ) {
        try {
            // 构建响应数据，包含分页信息和记录列表
            Map<String, Object> response = new HashMap<>();
            response.put("records", sqlTranslateService.getPagedHistory(page, pageSize));
            response.put("total", sqlTranslateService.getHistoryCount());
            response.put("page", page);
            response.put("pageSize", pageSize);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "获取历史记录失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    // 获取所有SQL执行记录
    @GetMapping("/executions")
    public ResponseEntity<?> getAllExecutions(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize
    ) {
        try {
            // 构建响应数据，包含分页信息和记录列表
            Map<String, Object> response = new HashMap<>();
            response.put("records", sqlTranslateService.getPagedExecutions(page, pageSize));
            response.put("total", sqlTranslateService.getExecutionsCount());
            response.put("page", page);
            response.put("pageSize", pageSize);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "获取SQL执行记录失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    // 获取SQL执行统计信息
    @GetMapping("/executions/statistics")
    public ResponseEntity<?> getExecutionStatistics() {
        try {
            return ResponseEntity.ok(sqlTranslateService.getExecutionStatistics());
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "获取执行统计信息失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    // 系统统计信息（用户数量，历史记录数量等）
    @GetMapping("/statistics")
    public ResponseEntity<?> getStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalUsers", userService.getUserCount());
            statistics.put("adminCount", userService.getUserCountByRole(UserRole.ROLE_ADMIN.name()));
            statistics.put("userCount", userService.getUserCountByRole(UserRole.ROLE_USER.name()));
            statistics.put("totalQueries", sqlTranslateService.getTotalQueriesCount());
            statistics.put("totalConnections", dbConnectionService.getTotalConnectionCount());
            
            return ResponseEntity.ok(statistics);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "获取统计信息失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    // 获取所有用户的数据库连接
    @GetMapping("/db-connections")
    public ResponseEntity<?> getAllDbConnections(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize
    ) {
        try {
            // 构建响应数据，包含分页信息和连接列表
            Map<String, Object> response = new HashMap<>();
            List<DbConnection> connections = dbConnectionService.getPagedConnections(page, pageSize);
            response.put("records", connections.stream()
                    .map(DbConnection::withoutPassword)
                    .collect(Collectors.toList()));
            response.put("total", dbConnectionService.getTotalConnectionCount());
            response.put("page", page);
            response.put("pageSize", pageSize);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "获取数据库连接失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    // 获取指定用户的数据库连接
    @GetMapping("/users/{userId}/db-connections")
    public ResponseEntity<?> getUserDbConnections(
            @PathVariable Long userId,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize
    ) {
        try {
            // 构建响应数据，包含分页信息和连接列表
            Map<String, Object> response = new HashMap<>();
            response.put("records", dbConnectionService.getPagedUserConnections(userId, page, pageSize));
            response.put("total", dbConnectionService.getUserConnectionCount(userId));
            response.put("page", page);
            response.put("pageSize", pageSize);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "获取用户数据库连接失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    // 测试指定数据库连接
    @PostMapping("/db-connections/{connectionId}/test")
    public ResponseEntity<?> testDbConnection(@PathVariable Long connectionId) {
        try {
            DbConnection connection = dbConnectionService.getConnectionByIdForAdmin(connectionId);
            dbConnectionService.testConnection(connection);
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "连接测试成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "连接测试失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    // 删除数据库连接
    @DeleteMapping("/db-connections/{connectionId}")
    public ResponseEntity<?> deleteDbConnection(@PathVariable Long connectionId) {
        try {
            dbConnectionService.deleteConnectionByAdmin(connectionId);
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "数据库连接已删除");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "删除连接失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    // 元数据管理相关API
    
    /**
     * 管理员接口：刷新所有元数据缓存
     */
    @PostMapping("/metadata/refresh-all")
    public ResponseEntity<?> refreshAllMetadata() {
        try {
            metadataService.refreshDefaultSchemaMetadata();
            Map<String, String> response = new HashMap<>();
            response.put("message", "所有元数据刷新已启动");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "刷新元数据失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 管理员接口：清理所有元数据缓存
     */
    @PostMapping("/metadata/clean-all")
    public ResponseEntity<?> cleanAllMetadata() {
        try {
            metadataService.cleanExpiredMetadata();
            Map<String, String> response = new HashMap<>();
            response.put("message", "所有元数据缓存已清理");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "清理元数据失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 清理所有SQL结果缓存
     */
    @PostMapping("/sql-cache/clean")
    public ResponseEntity<?> cleanAllSqlCache() {
        try {
            redisCacheUtil.clearAllSqlCache();
            Map<String, String> response = new HashMap<>();
            response.put("message", "成功清除所有SQL结果缓存");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "清理SQL结果缓存失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
} 